package com.yizhaosan.seckill.service.impl;

import com.yizhaosan.seckill.dao.SeckillDao;
import com.yizhaosan.seckill.dao.SuccessKilledDao;
import com.yizhaosan.seckill.dto.Exposer;
import com.yizhaosan.seckill.dto.SeckillExcution;
import com.yizhaosan.seckill.entity.Seckill;
import com.yizhaosan.seckill.entity.SuccessKilled;
import com.yizhaosan.seckill.enums.SeckillStatEnum;
import com.yizhaosan.seckill.exception.RepeatKillException;
import com.yizhaosan.seckill.exception.SeckillCloseException;
import com.yizhaosan.seckill.exception.SeckillException;
import com.yizhaosan.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 注入service依赖
    @Autowired
    private SeckillDao seckillDao;

    @Autowired
    private SuccessKilledDao successKilledDao;

    // MD5 加密slat
    private String slat = "";

    @Override
    public List<Seckill> getSeckillList() {

        return seckillDao.queryAll(0, 4);
    }

    @Override
    public Seckill getById(long seckillId) {

        return seckillDao.queryById(seckillId);
    }

    @Override
    public Exposer exportSeckillUrl(long seckillId) {

        Seckill seckill = seckillDao.queryById(seckillId);
        if (seckill == null) {
            return new Exposer(false, seckillId);
        }
        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();

        // 系统当前时间
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime()|| nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }

        // 生成随机盐，用于混淆MD5
        Random random = new Random();
        StringBuilder randomSlat = new StringBuilder(16);
        randomSlat.append(random.nextInt(99999999)).append(random.nextInt(99999999));
        int randomSlatLength = randomSlat.length();
        if (randomSlatLength < 16) {
            for (int i = 0; i < 16 - randomSlatLength; i++) {
                randomSlat.append("0");
            }
        }
        slat = randomSlat.toString();

        String md5 = getMD5(seckillId);
        return new Exposer(true, md5, seckillId);
    }

    @Override
    @Transactional
    /**
     * 使用注解控制事务方法的优点：
     * 1. 来发团队达成一致约定，明确标注事务方法的编程风格。
     * 2. 保证事务方法的执行时间尽可能的短，不要穿插其它的网络操作RPC/Http请求，或者剥离的事务方法外部。
     * 3. 不是所有的方法都需要事务，如只有一条修改操作、或者是只读操作 不需要事务控制。
     */
    public SeckillExcution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {

        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }
        // 执行秒杀逻辑：减库存、记录购买行为
        Date nowTime = new Date();

        try {
            // 减库存
            int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
            if (updateCount <= 0) {
                // 没有更新记录
                throw new SeckillCloseException("seckill is closed");
            } else {
                // 记录购买行为
                int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
                // 唯一seckillId和userPhone
                if (insertCount <= 0) {
                    // 重复秒杀
                    throw new RepeatKillException("seckill repeated");
                } else {
                    // 秒杀成功
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExcution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatKillException e2) {
          throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // 所有编译期异常转换为运行期异常
            throw new SeckillException("seckill inner error:" + e.getMessage());
        }
    }

    private String getMD5(long seckillId) {

        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }
}
